package element.synt;

import element.ast.AstNode;
import element.ast.DopNode;
import element.ast.PrimNode;
import element.base.Synt;
import element.base.TreeNode;
import element.base.Word;

//MulExp → UnaryExp | MulExp ('*' | '/' | '%') UnaryExp
public class MulExp extends Synt {
    public AstNode toAst() {
        if (this.isConst()) {
            return new PrimNode(this.calcu());
        }
        TreeNode node0 = this.getNodes().get(0);
        if (node0 instanceof UnaryExp) {
            return ((UnaryExp) node0).toAst();
        } else {
            UnaryExp right = (UnaryExp) this.getNodes().get(2);
            MulExp left = (MulExp) node0;
            String op = ((Word) this.getNodes().get(1)).getContent();
            AstNode leftNode = left.toAst();
            AstNode rightNode = right.toAst();
            return new DopNode(op, leftNode, rightNode);
        }
    }

    public int calcu() {
        TreeNode node0 = this.getNodes().get(0);
        if (node0 instanceof UnaryExp) {
            return ((UnaryExp) node0).calcu();
        } else {
            UnaryExp right = (UnaryExp) this.getNodes().get(2);
            MulExp left = (MulExp) node0;
            String op = ((Word) this.getNodes().get(1)).getContent();
            int leftvalue = left.calcu();
            int rightvalue = right.calcu();
            if (op.equals("*")) {
                return leftvalue * rightvalue;
            } else if (op.equals("/")) {
                return leftvalue / rightvalue;
            } else {
                return leftvalue % rightvalue;
            }
        }
    }

    public boolean isConst() {
        TreeNode node0 = this.getNodes().get(0);
        if (node0 instanceof UnaryExp) {
            return ((UnaryExp) node0).isConst();
        } else {
            UnaryExp right = (UnaryExp) this.getNodes().get(2);
            MulExp left = (MulExp) node0;
            return right.isConst() && left.isConst();
        }
    }
}
